package com.example.demo.arithmetic.datastructure.linkedlist2;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode() {}
 * ListNode(int val) { this.val = val; }
 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */

//给定一个已排序的链表的头 head ， 删除所有重复的元素
// ，使每个元素只出现一次 。返回 已排序的链表 。
// 输入：head = [1,2,3,3,4,4,5]
//输出：[1,2,3,4,5]
//输入：head = [1,1,1,2,3]
//输出：[1,2,3]
public class Leetcode83 {
    public static void main(String[] args) {
        ListNode head1 = new ListNode(3, null);
        ListNode head2 = new ListNode(2, head1);
        ListNode head3 = new ListNode(1, head2);
        ListNode head4 = new ListNode(1, head3);
        ListNode head5 = new ListNode(1, head4);
        ListNode head = new Leetcode83().deleteDuplicates(head5);
        while (head != null) {
            System.out.println(head.val);
            head = head.next;
        }
    }

    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        ListNode p1 = head;
        ListNode p2;
        while ((p2 = p1.next) != null) {
            if (p1.val == p2.val) {
                //删除p2
                p1.next = p2.next;
            } else {
                // 平移
                p1 = p1.next;
            }
        }
        return head;
    }

    /**
     * 递归
     * 太难理解 先不学
     *
     * @param p
     * @return
     */
//    public ListNode deleteDuplicates2(ListNode p) {
//        if (p == null || p.next == null) {
//            return p;
//        }
//
//
//    }
    public ListNode deleteDuplicates3(ListNode head) {
        if (head.next == null) {
            return head;
        }
        ListNode p1 = head;
        while ((p1.next) != null) {
            if (p1.val == p1.next.val) {
                //删除p2
                p1.next = p1.next.next;
            } else {
                // 平移
                p1 = p1.next;
            }
        }
        return head;
    }


    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
